{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 100 个 Python 小技巧\n",
    "\n",
    "\n",
    "\n",
    "**▍1、for循环中的else条件**\n",
    "\n",
    "\n",
    "\n",
    "这是一个for-else方法，循环遍历列表时使用else语句。\n",
    "\n",
    "\n",
    "\n",
    "下面举个例子，比如我们想检查一个列表中是否包含奇数。\n",
    "\n",
    "\n",
    "\n",
    "那么可以通过for循环，遍历查找。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n"
     ]
    }
   ],
   "source": [
    "numbers = [2, 4, 6, 8, 1]\n",
    "\n",
    "for number in numbers:\n",
    "    if number % 2 == 1:\n",
    "        print(number)\n",
    "        break\n",
    "else:\n",
    "    print(\"No odd numbers\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果找到了奇数，就会打印该数值，并且执行break语句，跳过else语句。\n",
    "\n",
    "\n",
    "\n",
    "没有的话，就不会执行break语句，而是执行else语句。\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "**▍2、从列表中获取元素，定义多个变量**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "my_list = [1, 2, 3, 4, 5]\n",
    "one, two, three, four, five = my_list\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍3、使用heapq模块，获取列表中n个最大或最小的元素**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[91, 87, 82]\n",
      "[15, 33, 33, 49, 51]\n"
     ]
    }
   ],
   "source": [
    "import heapq\n",
    "\n",
    "scores = [51, 33, 64, 87, 91, 75, 15, 49, 33, 82]\n",
    "\n",
    "print(heapq.nlargest(3, scores))  # [91, 87, 82]\n",
    "print(heapq.nsmallest(5, scores))  # [15, 33, 33, 49, 51]\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍4、将列表中的所有元素作为参数传递给函数**\n",
    "\n",
    "\n",
    "\n",
    "我们可以使用 * 号，提取列表中所有的元素\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3, 4]\n",
      "1 2 3 4\n"
     ]
    }
   ],
   "source": [
    "my_list = [1, 2, 3, 4]\n",
    "\n",
    "print(my_list)  # [1, 2, 3, 4]\n",
    "print(*my_list)  # 1 2 3 4\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如此便可以将列表中的所有元素，作为参数传递给函数\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10\n"
     ]
    }
   ],
   "source": [
    "def sum_of_elements(*arg):\n",
    "    total = 0\n",
    "    for i in arg:\n",
    "        total += i\n",
    "\n",
    "    return total\n",
    "\n",
    "\n",
    "result = sum_of_elements(*[1, 2, 3, 4])\n",
    "print(result)  # 10\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍5、获取列表的所有中间元素**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[2, 3, 4, 5, 6, 7]\n"
     ]
    }
   ],
   "source": [
    "_, *elements_in_the_middle, _ = [1, 2, 3, 4, 5, 6, 7, 8]\n",
    "print(elements_in_the_middle)  # [2, 3, 4, 5, 6, 7]\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍6、****使用一行代码赋值多个变量**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "one, two, three, four = 1, 2, 3, 4\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍7、列表推导式**\n",
    "\n",
    "\n",
    "\n",
    "只用一行代码，便可完成对数组的迭代以及运算。\n",
    "\n",
    "\n",
    "\n",
    "比如，将列表中的每个数字提高一倍。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 4, 9, 16, 25]\n"
     ]
    }
   ],
   "source": [
    "numbers = [1, 2, 3, 4, 5]\n",
    "squared_numbers = [num * num for num in numbers]\n",
    "\n",
    "print(squared_numbers) # [1, 4, 9, 16, 25]\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "推导式不仅列表能用，字典、集合、生成器也能使用。\n",
    "\n",
    "\n",
    "\n",
    "下面看一下，使用字典推导式，将字典的值提高一倍。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'a': 16, 'b': 25}\n"
     ]
    }
   ],
   "source": [
    "dictionary = {'a': 4, 'b': 5}\n",
    "squared_dictionary = {key: num * num for (key, num) in dictionary.items()}\n",
    "\n",
    "print(squared_dictionary)  # {'a': 16, 'b': 25}\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍8、通过Enum枚举同一标签或一系列常量的集合**\n",
    "\n",
    "\n",
    "\n",
    "枚举是绑定到唯一的常量值的一组符号名称(成员)。\n",
    "\n",
    "\n",
    "\n",
    "在枚举中，成员可以通过身份进行比较，枚举本身可以迭代。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "IN_PROGRESS\n",
      "2\n"
     ]
    }
   ],
   "source": [
    "from enum import Enum\n",
    "\n",
    "\n",
    "class Status(Enum):\n",
    "    NO_STATUS = -1\n",
    "    NOT_STARTED = 0\n",
    "    IN_PROGRESS = 1\n",
    "    COMPLETED = 2\n",
    "\n",
    "\n",
    "print(Status.IN_PROGRESS.name)  # IN_PROGRESS\n",
    "print(Status.COMPLETED.value)  # 2\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍9、****重复字符串**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "BananaBananaBananaBanana\n"
     ]
    }
   ],
   "source": [
    "name = \"Banana\"\n",
    "print(name * 4)  # BananaBananaBananaBanana\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍10、比较3个数字的大小**\n",
    "\n",
    "\n",
    "\n",
    "如果想比较一个值和其他两个值的大小情况，你可以使用简单的数学表达式。 `1 < x < 10`\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这个是最简单的代数表达式，在Python中也是可以使用的。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "x = 3\n",
    "\n",
    "print(1 < x < 10)  # True\n",
    "print(1 < x and x < 10)  # True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍11、使用1行代码合并字典**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'name': 'Fan', 'location': 'Guangdong, Guangzhou', 'surname': 'Xiao'}\n"
     ]
    }
   ],
   "source": [
    "first_dictionary = {'name': 'Fan', 'location': 'Guangzhou'}\n",
    "second_dictionary = {'name': 'Fan', 'surname': 'Xiao', 'location': 'Guangdong, Guangzhou'}\n",
    "\n",
    "# python 3.8+ 支持\n",
    "result = first_dictionary | second_dictionary\n",
    "\n",
    "print(result)\n",
    "# {'name': 'Fan', 'location': 'Guangdong, Guangzhou', 'surname': 'Xiao'}\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍12、查找元组中元素的索引**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3\n"
     ]
    }
   ],
   "source": [
    "books = ('Atomic habits', 'Ego is the enemy', 'Outliers', 'Mastery')\n",
    "\n",
    "print(books.index('Mastery'))   # 3\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍13、将字符串转换为字符串列表**\n",
    "\n",
    "\n",
    "\n",
    "假设你在函数中获得输出，原本应该是一个列表，但实际上却是一个字符串。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "input = \"[1,2,3]\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "你可能第一时间会想到使用索引或者正则表达式。\n",
    "\n",
    "\n",
    "\n",
    "实际上，使用ast模块的literal_eval方法就能搞定。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3]\n",
      "[[1, 2, 3], [4, 5, 6]]\n"
     ]
    }
   ],
   "source": [
    "import ast\n",
    "\n",
    "\n",
    "def string_to_list(string):\n",
    "    return ast.literal_eval(string)\n",
    "\n",
    "\n",
    "string = \"[1, 2, 3]\"\n",
    "my_list = string_to_list(string)\n",
    "print(my_list)  # [1, 2, 3]\n",
    "\n",
    "string = \"[[1, 2, 3],[4, 5, 6]]\"\n",
    "my_list = string_to_list(string)\n",
    "print(my_list)  # [[1, 2, 3], [4, 5, 6]]\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍14、****计算两数差值**\n",
    "\n",
    "\n",
    "\n",
    "计算出2个数字之间的差值。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-2\n",
      "2\n"
     ]
    }
   ],
   "source": [
    "def subtract(a, b):\n",
    "    return a - b\n",
    "\n",
    "\n",
    "print((subtract(1, 3)))  # -2\n",
    "print((subtract(3, 1)))  # 2\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "上面的这个方法，需要考虑数值的先后顺序。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-2\n",
      "-2\n"
     ]
    }
   ],
   "source": [
    "def subtract(a, b):\n",
    "    return a - b\n",
    "\n",
    "\n",
    "print((subtract(a=1, b=3)))  # -2\n",
    "print((subtract(b=3, a=1)))  # -2\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "使用命名参数，安排顺序，这样就不会出错了。\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "**▍15、****用一个print()语句打印多个元素**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1 2 3 a z this is here here is something else\n"
     ]
    }
   ],
   "source": [
    "print(1, 2, 3, \"a\", \"z\", \"this is here\", \"here is something else\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍16、****在同一行打印多个元素**\n",
    "\n",
    "**\n",
    "**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "HelloWorld\n",
      "Hello World\n",
      "words, with, commas, in, between\n"
     ]
    }
   ],
   "source": [
    "print(\"Hello\", end=\"\")\n",
    "print(\"World\")  # HelloWorld\n",
    "\n",
    "print(\"Hello\", end=\" \")\n",
    "print(\"World\")  # Hello World\n",
    "\n",
    "print('words',   'with', 'commas', 'in', 'between', sep=', ')\n",
    "# words, with, commas, in, between\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍17、****打印多个值，在每个值之间使用自定义分隔符**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "29/01/2022\n",
      "name@domain.com\n"
     ]
    }
   ],
   "source": [
    "print(\"29\", \"01\", \"2022\", sep=\"/\")  # 29/01/2022\n",
    "\n",
    "print(\"name\", \"domain.com\", sep=\"@\")  # name@domain.com\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "▍18、不能在变量名的开头使用数字\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "invalid decimal literal (Temp/ipykernel_20840/1195974738.py, line 3)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;36m  File \u001b[1;32m\"C:\\Users\\yulike\\AppData\\Local\\Temp/ipykernel_20840/1195974738.py\"\u001b[1;36m, line \u001b[1;32m3\u001b[0m\n\u001b[1;33m    4_letters = \"abcd\" # this doesn’t work\u001b[0m\n\u001b[1;37m     ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid decimal literal\n"
     ]
    }
   ],
   "source": [
    "four_letters = \"abcd\" # this works\n",
    "\n",
    "4_letters = \"abcd\" # this doesn’t work\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这是Python的变量命名规则。\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "**▍19、不能在变量名的开头使用运算符**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "cannot assign to operator (Temp/ipykernel_20840/3713648192.py, line 1)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;36m  File \u001b[1;32m\"C:\\Users\\yulike\\AppData\\Local\\Temp/ipykernel_20840/3713648192.py\"\u001b[1;36m, line \u001b[1;32m1\u001b[0m\n\u001b[1;33m    +variable = \"abcd\"  # this doesn’t work\u001b[0m\n\u001b[1;37m    ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m cannot assign to operator\n"
     ]
    }
   ],
   "source": [
    "+variable = \"abcd\"  # this doesn’t work\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍20、****数字的第一位不能是0**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers (Temp/ipykernel_20840/2867550321.py, line 1)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;36m  File \u001b[1;32m\"C:\\Users\\yulike\\AppData\\Local\\Temp/ipykernel_20840/2867550321.py\"\u001b[1;36m, line \u001b[1;32m1\u001b[0m\n\u001b[1;33m    number = 0110 # this doesn't work\u001b[0m\n\u001b[1;37m                ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers\n"
     ]
    }
   ],
   "source": [
    "number = 0110 # this doesn't work\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这个确实挺神奇的。\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "**▍21、****在变量名的任何地方使用下划线**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [],
   "source": [
    "a______b = \"abcd\"  # this works\n",
    "_a_b_c_d = \"abcd\"  # this also works\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这并不意味着，你可以无限使用，为了代码的易读性，还是需要合理使用。\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "**▍22、使用下划线分割数值较大的数字**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1000000000\n",
      "1234567\n"
     ]
    }
   ],
   "source": [
    "print(1_000_000_000)  # 1000000000\n",
    "print(1_234_567)  # 1234567\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如此，看到一大堆数字时，也能轻松阅读。\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "**▍23、反转列表**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['d', 'c', 'b', 'a']\n"
     ]
    }
   ],
   "source": [
    "my_list = ['a', 'b', 'c', 'd']\n",
    "\n",
    "my_list.reverse()\n",
    "\n",
    "print(my_list)  # ['d', 'c', 'b', 'a']\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍24、使用步进函数对字符串切片**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "This \n",
      "Tssu\n"
     ]
    }
   ],
   "source": [
    "my_string = \"This is just a sentence\"\n",
    "print(my_string[0:5])  # This\n",
    "\n",
    "# Take three steps forward\n",
    "print(my_string[0:10:3])  # Tsse\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍25、反向****切片**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "suj si sih\n",
      "sjs i\n"
     ]
    }
   ],
   "source": [
    "my_string = \"This is just a sentence\"\n",
    "print(my_string[10:0:-1])  # suj si sih\n",
    "\n",
    "# Take two steps forward\n",
    "print(my_string[10:0:-2])  # sjs i\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍26、使用开始或结束索引进行切片**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " is just a sentence\n",
      "Thi\n"
     ]
    }
   ],
   "source": [
    "my_string = \"This is just a sentence\"\n",
    "print(my_string[4:])  # is just a sentence\n",
    "\n",
    "print(my_string[:3])  # Thi\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍27、** **/和//的区别**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1.5\n",
      "1\n"
     ]
    }
   ],
   "source": [
    "print(3/2)  # 1.5\n",
    "print(3//2)  # 1\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍28、==和is的区别**\n",
    "\n",
    "\n",
    "\n",
    "is：检查两个变量是否指向同一对象内存中\n",
    "\n",
    "==：比较两个对象的值\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "False\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "first_list = [1, 2, 3]\n",
    "second_list = [1, 2, 3]\n",
    "\n",
    "# 比较两个值\n",
    "print(first_list == second_list)  # True\n",
    "\n",
    "# 是否指向同一内存\n",
    "print(first_list is second_list)  \n",
    "# False\n",
    "\n",
    "\n",
    "third_list = first_list\n",
    "\n",
    "print(third_list is first_list)  \n",
    "# True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍29、合并字典**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'a': 1, 'b': 2, 'c': 3, 'd': 4}\n"
     ]
    }
   ],
   "source": [
    "dictionary_one = {\"a\": 1, \"b\": 2}\n",
    "dictionary_two = {\"c\": 3, \"d\": 4}\n",
    "\n",
    "merged = {**dictionary_one, **dictionary_two}\n",
    "\n",
    "print(merged)  # {'a': 1, 'b': 2, 'c': 3, 'd': 4}\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍30、检查字符串是否大于另一字符串**\n",
    "\n",
    "**\n",
    "**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "False\n"
     ]
    }
   ],
   "source": [
    "first = \"abc\"\n",
    "second = \"def\"\n",
    "\n",
    "print(first < second)  # True\n",
    "\n",
    "second = \"ab\"\n",
    "print(first < second)  # False\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍31、检查字符串是否以特定字符开头(不使用索引)**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n"
     ]
    }
   ],
   "source": [
    "my_string = \"abcdef\"\n",
    "print(my_string.startswith(\"b\"))  # False\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍32、使用id()查找变量的唯一id**\n",
    "\n",
    "**\n",
    "**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1584744261936\n",
      "1584744261968\n",
      "1584749748144\n"
     ]
    }
   ],
   "source": [
    "print(id(1))  # 4325776624\n",
    "print(id(2))  # 4325776656\n",
    "print(id(\"string\"))  # 4327978288\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍33、整数、浮点数、字符串、布尔值和元组都是不可变的**\n",
    "\n",
    "\n",
    "\n",
    "当变量被赋值为整数、浮点数、字符串、布尔值、元组这些不可变类型后，该变量就会指向一个内存对象。\n",
    "\n",
    "\n",
    "\n",
    "如果重新给变量再赋值，它的内存对象就会发生改变。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1584744261936\n",
      "1584744261936\n",
      "1584744262000\n",
      "1584744261936\n"
     ]
    }
   ],
   "source": [
    "number = 1\n",
    "print(id(number))  # 4325215472\n",
    "print(id(1))  # 4325215472\n",
    "\n",
    "number = 3\n",
    "print(id(number))  # 4325215536\n",
    "print(id(1))  # 4325215472\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍34、字符串和元组也是不可变的**\n",
    "\n",
    "\n",
    "\n",
    "此处再说明一次。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1584817581040\n",
      "1584817581808\n"
     ]
    }
   ],
   "source": [
    "name = \"Fatos\"\n",
    "print(id(name))  # 4422282544\n",
    "\n",
    "name = \"fatos\"\n",
    "print(id(name))  # 4422346608\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍35、列表、集合和字典都是可变的**\n",
    "\n",
    "\n",
    "\n",
    "这意味着发生更改时，不会改变其内存对象。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1584817587520\n",
      "1584817587520\n"
     ]
    }
   ],
   "source": [
    "cities = [\"Beijing\", \"Guangzhou\", \"chengdu\"]\n",
    "print(id(cities))  # 4482699712\n",
    "\n",
    "cities.append(\"Beijing\")\n",
    "print(id(cities))  # 4482699712\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "下面是字典。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1584817675392\n",
      "1584817675392\n"
     ]
    }
   ],
   "source": [
    "my_set = {1, 2, 3, 4}\n",
    "print(id(my_set))  # 4352726176\n",
    "\n",
    "my_set.add(5)\n",
    "print(id(my_set))  # 4352726176\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍36、把一个列表变成不可变的列表**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "ename": "AttributeError",
     "evalue": "'frozenset' object has no attribute 'add'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mAttributeError\u001b[0m                            Traceback (most recent call last)",
      "\u001b[1;32m~\\AppData\\Local\\Temp/ipykernel_20840/3871927203.py\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m      1\u001b[0m \u001b[0mmy_set\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mfrozenset\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;34m'a'\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;34m'b'\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;34m'c'\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;34m'd'\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      2\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 3\u001b[1;33m \u001b[0mmy_set\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0madd\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"a\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mAttributeError\u001b[0m: 'frozenset' object has no attribute 'add'"
     ]
    }
   ],
   "source": [
    "my_set = frozenset(['a', 'b', 'c', 'd'])\n",
    "\n",
    "my_set.add(\"a\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "使用frozenset()后，你就无法更改了。\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "**▍37、if-elif块可以在没有else块的情况下存在**\n",
    "\n",
    "\n",
    "\n",
    "但是elif不能在没有if语句之前独立存在。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Positive\n"
     ]
    }
   ],
   "source": [
    "def check_number(number):\n",
    "    if number > 0:\n",
    "        return \"Positive\"\n",
    "    elif number == 0:\n",
    "        return \"Zero\"\n",
    "\n",
    "    return \"Negative\"\n",
    "\n",
    "\n",
    "print(check_number(1))  # Positive\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍38、使用sorted()检查2个字符串是否为相同**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "True\n",
      "False\n"
     ]
    }
   ],
   "source": [
    "def check_if_anagram(first_word, second_word):\n",
    "    first_word = first_word.lower()\n",
    "    second_word = second_word.lower()\n",
    "    return sorted(first_word) == sorted(second_word)\n",
    "\n",
    "\n",
    "print(check_if_anagram(\"testinG\", \"Testing\"))  # True\n",
    "print(check_if_anagram(\"Here\", \"Rehe\"))  # True\n",
    "print(check_if_anagram(\"Know\", \"Now\"))  # False\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍39、获取字符的Unicode值**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "65\n",
      "66\n",
      "67\n",
      "97\n"
     ]
    }
   ],
   "source": [
    "print(ord(\"A\"))  # 65\n",
    "print(ord(\"B\"))  # 66\n",
    "print(ord(\"C\"))  # 66\n",
    "print(ord(\"a\"))  # 97\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍40、获取字典的键**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['a', 'b', 'c']\n"
     ]
    }
   ],
   "source": [
    "dictionary = {\"a\": 1, \"b\": 2, \"c\": 3}\n",
    "\n",
    "keys = dictionary.keys()\n",
    "print(list(keys))  # ['a', 'b', 'c']\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍41、获取字典的值**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3]\n"
     ]
    }
   ],
   "source": [
    "dictionary = {\"a\": 1, \"b\": 2, \"c\": 3}\n",
    "\n",
    "values = dictionary.values()\n",
    "print(list(values))  # [1, 2, 3]\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍42、交换字典的键、值位置**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{1: 'a', 2: 'b', 3: 'c'}\n"
     ]
    }
   ],
   "source": [
    "dictionary = {\"a\": 1, \"b\": 2, \"c\": 3}\n",
    "\n",
    "reversed_dictionary = {j: i for i, j in dictionary.items()}\n",
    "print(reversed_dictionary)  # {1: 'a', 2: 'b', 3: 'c'}\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍43、将布尔值转换为数字**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n",
      "1.0\n"
     ]
    }
   ],
   "source": [
    "print(int(False))  # 0\n",
    "print(float(True))  # 1.0\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍44、在算术运算中使用布尔值**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.8333333333333334\n"
     ]
    }
   ],
   "source": [
    "x = 10\n",
    "y = 12\n",
    "\n",
    "result = (x - False)/(y * True)\n",
    "print(result)  # 0.8333333333333334\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍45、将任何数据类型转换为布尔值**\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n",
      "True\n",
      "True\n",
      "True\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "print(bool(.0))  # False\n",
    "print(bool(3))  # True\n",
    "print(bool(\"-\"))  # True\n",
    "print(bool(\"string\"))  # True\n",
    "print(bool(\" \"))  # True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍46、将值转换为复数**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(10+2j)\n"
     ]
    }
   ],
   "source": [
    "print(complex(10, 2))  # (10+2j)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "也可以将数字转换为十六进制数。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0xb\n"
     ]
    }
   ],
   "source": [
    "print(hex(11))  # 0xb\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍47、在列表的第一个位置添加一个值**\n",
    "\n",
    "\n",
    "\n",
    "如果使用append()，将从列表的最后一个位置插入新值。\n",
    "\n",
    "\n",
    "\n",
    "可以通过使用insert()，来指定插入新元素的索引和数值。\n",
    "\n",
    "\n",
    "\n",
    "那么列表的第一个位置为0，即下标为0。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[2, 3, 4, 5, 6]\n"
     ]
    }
   ],
   "source": [
    "my_list = [3, 4, 5]\n",
    "\n",
    "my_list.append(6)\n",
    "my_list.insert(0, 2)\n",
    "print(my_list)  # [2, 3, 4, 5, 6]\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍48、Lambda函数只能在一行代码中**\n",
    "\n",
    "\n",
    "\n",
    "无法通过多行代码，来使用lambda函数。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [
    {
     "ename": "IndentationError",
     "evalue": "unindent does not match any outer indentation level (<tokenize>, line 3)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;36m  File \u001b[1;32m\"<tokenize>\"\u001b[1;36m, line \u001b[1;32m3\u001b[0m\n\u001b[1;33m    else:\u001b[0m\n\u001b[1;37m    ^\u001b[0m\n\u001b[1;31mIndentationError\u001b[0m\u001b[1;31m:\u001b[0m unindent does not match any outer indentation level\n"
     ]
    }
   ],
   "source": [
    "comparison = lambda x: if x > 3:\n",
    "                    print(\"x > 3\")\n",
    "                else:\n",
    "                    print(\"x is not greater than 3\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "报错。\n",
    "\n",
    "\n",
    "\n",
    "![图片](https://mmbiz.qpic.cn/mmbiz_png/y0SBuxfLhakdhAhYOXSibK8SicSPnaGPh1nTicSISTwEv8WAREB1pgfZhibsj1IxYgx7rMnfwMkYB36HTRuG1mOkEQ/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1)\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "**▍49、Lambda中的条件语句应始终包含else语句**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "invalid syntax (Temp/ipykernel_20840/1070169197.py, line 1)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;36m  File \u001b[1;32m\"C:\\Users\\yulike\\AppData\\Local\\Temp/ipykernel_20840/1070169197.py\"\u001b[1;36m, line \u001b[1;32m1\u001b[0m\n\u001b[1;33m    comparison = lambda x: \"x > 3\" if x > 3\u001b[0m\n\u001b[1;37m                                           ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n"
     ]
    }
   ],
   "source": [
    "comparison = lambda x: \"x > 3\" if x > 3"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "运行上面的代码，报错。\n",
    "\n",
    "\n",
    "\n",
    "![图片]()\n",
    "\n",
    "\n",
    "\n",
    "这是由于条件表达式的特性，而不是lambda的导致的。\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "**▍50、使用filter()，获得一个新对象**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 3]\n",
      "[1, 2, 3, 4]\n"
     ]
    }
   ],
   "source": [
    "my_list = [1, 2, 3, 4]\n",
    "\n",
    "odd = filter(lambda x: x % 2 == 1, my_list)\n",
    "\n",
    "print(list(odd))   # [1, 3]\n",
    "print(my_list)  # [1, 2, 3, 4]\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍51、map****()返回一个新对象**\n",
    "\n",
    "\n",
    "\n",
    "map()函数将给定函数应用于可迭代对象(列表、元组等)，然后返回结果(map对象)。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 4, 9, 16]\n",
      "[1, 2, 3, 4]\n"
     ]
    }
   ],
   "source": [
    "my_list = [1, 2, 3, 4]\n",
    "\n",
    "squared = map(lambda x: x ** 2, my_list)\n",
    "\n",
    "print(list(squared))   # [1, 4, 9, 16]\n",
    "print(my_list)  # [1, 2, 3, 4]\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍52、range()的step参数**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1 4 7 "
     ]
    }
   ],
   "source": [
    "for number in range(1, 10, 3):\n",
    "    print(number, end=\" \")\n",
    "# 1 4 7\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍53、range()默认从0开始**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 74,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 1 2 0 1 2 "
     ]
    }
   ],
   "source": [
    "def range_with_zero(number):\n",
    "    for i in range(0, number):\n",
    "        print(i, end=' ')\n",
    "\n",
    "\n",
    "def range_with_no_zero(number):\n",
    "    for i in range(number):\n",
    "        print(i, end=' ')\n",
    "\n",
    "\n",
    "range_with_zero(3)  # 0 1 2\n",
    "range_with_no_zero(3)  # 0 1 2\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍54、不需要和0比较长度**\n",
    "\n",
    "\n",
    "\n",
    "如果长度大于0，则默认为True。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 75,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
   "source": [
    "def get_element_with_comparison(my_list):\n",
    "    if len(my_list) > 0:\n",
    "        return my_list[0]\n",
    "\n",
    "\n",
    "def get_first_element(my_list):\n",
    "    if len(my_list):\n",
    "        return my_list[0]\n",
    "\n",
    "\n",
    "elements = [1, 2, 3, 4]\n",
    "first_result = get_element_with_comparison(elements)\n",
    "second_result = get_element_with_comparison(elements)\n",
    "\n",
    "print(first_result == second_result)  # True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍55、可以在同一个作用域内多次定义一个方法**\n",
    "\n",
    "\n",
    "\n",
    "但是，只有最后一个会被调用，覆盖以前。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 76,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Third address\n"
     ]
    }
   ],
   "source": [
    "def get_address():\n",
    "    return \"First address\"\n",
    "\n",
    "\n",
    "def get_address():\n",
    "    return \"Second address\"\n",
    "\n",
    "\n",
    "def get_address():\n",
    "    return \"Third address\"\n",
    "\n",
    "\n",
    "print(get_address())  # Third address\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍56、在外部直接访问私有属性**\n",
    "\n",
    "\n",
    "\n",
    "在定义属性或方法时，在属性名或者方法名前增加两个下划线，定义的就是私有属性或方法。\n",
    "\n",
    "\n",
    "\n",
    "如果想要在外部访问，那么只需要在名称前面加上 '_类名' 变成 '_类名__名称'。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "62000\n"
     ]
    }
   ],
   "source": [
    "class Engineer:\n",
    "    def __init__(self, name):\n",
    "        self.name = name\n",
    "        self.__starting_salary = 62000\n",
    "\n",
    "\n",
    "dain = Engineer('Dain')\n",
    "print(dain._Engineer__starting_salary)  # 62000\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍57、检查对象的内存使用情况**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 78,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "56\n"
     ]
    }
   ],
   "source": [
    "import sys\n",
    "\n",
    "print(sys.getsizeof(\"bitcoin\"))  # 56\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍58、定义一个方法，可以调用任意个参数**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 79,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "6\n",
      "15\n",
      "28\n"
     ]
    }
   ],
   "source": [
    "def get_sum(*arguments):\n",
    "    result = 0\n",
    "    for i in arguments:\n",
    "        result += i\n",
    "    return result\n",
    "\n",
    "\n",
    "print(get_sum(1, 2, 3))  # 6\n",
    "print(get_sum(1, 2, 3, 4, 5))  # 15\n",
    "print(get_sum(1, 2, 3, 4, 5, 6, 7))  # 28\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍59、使用super()或父类的名称调用父类的初始化**\n",
    "\n",
    "\n",
    "\n",
    "使用super函数调用父类的初始化方法。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 80,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Tsinghua University\n"
     ]
    }
   ],
   "source": [
    "class Parent:\n",
    "    def __init__(self, city, address):\n",
    "        self.city = city\n",
    "        self.address = address\n",
    "\n",
    "\n",
    "class Child(Parent):\n",
    "    def __init__(self, city, address, university):\n",
    "        super().__init__(city, address)\n",
    "        self.university = university\n",
    "\n",
    "\n",
    "child = Child('Peking University', 'Fudan University', 'Tsinghua University')\n",
    "print(child.university)  # Tsinghua University\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "使用父类的名称调用父类。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 81,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Tsinghua University\n"
     ]
    }
   ],
   "source": [
    "class Parent:\n",
    "    def __init__(self, city, address):\n",
    "        self.city = city\n",
    "        self.address = address\n",
    "\n",
    "\n",
    "class Child(Parent):\n",
    "    def __init__(self, city, address, university):\n",
    "        Parent.__init__(self, city, address)\n",
    "        self.university = university\n",
    "\n",
    "\n",
    "child = Child('Peking University', 'Fudan University', 'Tsinghua University')\n",
    "print(child.university)  # Tsinghua University\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍60、在类中使用 + 操作符**\n",
    "\n",
    "\n",
    "\n",
    "在两个int数据类型之间使用 + 运算符时，将得到它们的和。\n",
    "\n",
    "\n",
    "\n",
    "而在两个字符串数据类型之间使用它时，会将其合并。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 82,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "11\n",
      "firstsecond\n"
     ]
    }
   ],
   "source": [
    "print(10 + 1)  # 两数相加\n",
    "print('first' + 'second')  # 字符串相加\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这个就是操作符重载，你还可以在类中使用(__add__)。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 91,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "rent: 2000 groceries:500\n"
     ]
    }
   ],
   "source": [
    "class Expenses:\n",
    "    def __init__(self, rent, groceries):\n",
    "        self.rent = rent\n",
    "        self.groceries = groceries\n",
    "    def __repr__(self):\n",
    "        return f\"rent: {self.rent} groceries:{self.groceries}\"\n",
    "    def __add__(self, other):\n",
    "        return Expenses(self.rent + other.rent, self.groceries + other.groceries)\n",
    "\n",
    "april_expenses = Expenses(1000, 200)\n",
    "may_expenses = Expenses(1000, 300)\n",
    "total_expenses = april_expenses + may_expenses\n",
    "print(total_expenses)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍61、在类中使用 < 和 == 操作符**\n",
    "\n",
    "\n",
    "\n",
    "下面定义一个操作重载示例( < 操作符)，使用__lt__方法。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 84,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
   "source": [
    "class Game:\n",
    "    def __init__(self, score):\n",
    "        self.score = score\n",
    "\n",
    "    def __lt__(self, other):\n",
    "        return self.score < other.score\n",
    "\n",
    "\n",
    "first = Game(1)\n",
    "second = Game(2)\n",
    "\n",
    "print(first < second)  # True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "同样的，== 操作符使用__eq__方法。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 85,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n"
     ]
    }
   ],
   "source": [
    "class Journey:\n",
    "    def __init__(self, location, destination, duration):\n",
    "        self.location = location\n",
    "        self.destination = destination\n",
    "        self.duration = duration\n",
    "\n",
    "    def __eq__(self, other):\n",
    "        return ((self.location == other.location) and\n",
    "                (self.destination == other.destination) and\n",
    "                (self.duration == other.duration))\n",
    "\n",
    "\n",
    "first = Journey('Location A', 'Destination A', '30min')\n",
    "second = Journey('Location B', 'Destination B', '30min')\n",
    "\n",
    "print(first == second)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "还有一些其他的定义。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "__sub__() for -\n",
    "__mul__() for *\n",
    "__truediv__() for /\n",
    "__ne__() for !=\n",
    "__ge__() for >=\n",
    "__gt__() for >"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍62、为类的对象定义自定义的可打印版本**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 92,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "'Rectangle with area=12'\n"
     ]
    }
   ],
   "source": [
    "class Rectangle:\n",
    "    def __init__(self, a, b):\n",
    "        self.a = a\n",
    "        self.b = b\n",
    "\n",
    "    def __repr__(self):\n",
    "        return repr('Rectangle with area=' + str(self.a * self.b))\n",
    "\n",
    "\n",
    "print(Rectangle(3, 4))  # 'Rectangle with area=12'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍63、交换字符串中字符的大小写**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 93,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tHIS IS JUST A SENTENCE.\n"
     ]
    }
   ],
   "source": [
    "string = \"This is just a sentence.\"\n",
    "result = string.swapcase()\n",
    "\n",
    "print(result)  # tHIS IS JUST A SENTENCE.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍64、检查字符串是否都是空格**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 94,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    }
   ],
   "source": [
    "string = \"  \"\n",
    "result = string.isspace()\n",
    "\n",
    "print(result)  # True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍65、检查字符串是否都是字母或数字**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 95,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "False\n",
      "True\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "name = \"Password\"\n",
    "print(name.isalnum())  # True\n",
    "\n",
    "name = \"Secure Password \"\n",
    "print(name.isalnum())  # False\n",
    "\n",
    "name = \"S3cur3P4ssw0rd\"\n",
    "print(name.isalnum())  # True\n",
    "\n",
    "name = \"133\"\n",
    "print(name.isalnum())  # True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍66、检查字符串是否都是字母**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 96,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "False\n",
      "False\n"
     ]
    }
   ],
   "source": [
    "string = \"Name\"\n",
    "print(string.isalpha())  # True\n",
    "\n",
    "string = \"Firstname Lastname\"\n",
    "print(string.isalpha())  # False\n",
    "\n",
    "string = \"P4ssw0rd\"\n",
    "print(string.isalpha())  # False\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍67、根据参数删除字符**\n",
    "\n",
    "\n",
    "\n",
    "从右侧开始。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 97,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "This is a sentence with\n",
      "this here is a sentence…\n"
     ]
    }
   ],
   "source": [
    "string = \"This is a sentence with       \"\n",
    "print(string.rstrip())  # \"This is a sentence with\"\n",
    "\n",
    "string = \"this here is a sentence…..,,,,aaaaasd\"\n",
    "print(string.rstrip(\".,dsa\"))  # \"this here is a sentence\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "同样的，左侧也能操作。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 98,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "First\n"
     ]
    }
   ],
   "source": [
    "string = \"ffffffffFirst\"\n",
    "print(string.lstrip(\"f\"))  # First\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍68、检查字符串是否为数字**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 99,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n",
      "True\n",
      "False\n",
      "False\n"
     ]
    }
   ],
   "source": [
    "string = \"seven\"\n",
    "print(string.isdigit())  # False\n",
    "\n",
    "string = \"1337\"\n",
    "print(string.isdigit())  # True\n",
    "\n",
    "string = \"5a\"\n",
    "print(string.isdigit())  # False\n",
    "\n",
    "string = \"2**5\"\n",
    "print(string.isdigit())  # False\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍69、检查字符串是否为中文数字**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 100,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "# 42673\n",
    "string = \"四二六七三\"\n",
    "\n",
    "print(string.isdigit())  # False\n",
    "print(string.isnumeric())  # True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍70、检查字符串是否所有单词都是大写开头**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 101,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n",
      "True\n",
      "False\n",
      "False\n"
     ]
    }
   ],
   "source": [
    "string = \"This is a sentence\"\n",
    "print(string.istitle())  # False\n",
    "\n",
    "string = \"10 Python Tips\"\n",
    "print(string.istitle())  # True\n",
    "\n",
    "string = \"How to Print A String in Python\"\n",
    "# False\n",
    "print(string.istitle())\n",
    "\n",
    "string = \"PYTHON\"\n",
    "print(string.istitle())  # False\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍71、在元组中使用负索引**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 102,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "4\n",
      "1\n"
     ]
    }
   ],
   "source": [
    "numbers = (1, 2, 3, 4)\n",
    "\n",
    "print(numbers[-1])  # 4\n",
    "print(numbers[-4])  # 1\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍72、在元组中嵌套列表和元组**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 103,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['first', 'second', 'third']\n",
      "('aaaaaaaaaa', 3, 4)\n"
     ]
    }
   ],
   "source": [
    "mixed_tuple = ((\"a\"*10, 3, 4), ['first', 'second', 'third'])\n",
    "\n",
    "print(mixed_tuple[1])  # ['first', 'second', 'third']\n",
    "print(mixed_tuple[0])  # ('aaaaaaaaaa', 3, 4)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍73、快速统计元素在列表中出现的次数**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 104,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n"
     ]
    }
   ],
   "source": [
    "names = [\"Besim\", \"Albert\", \"Besim\", \"Fisnik\", \"Meriton\"]\n",
    "\n",
    "print(names.count(\"Besim\"))  # 2\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍74、使用slice()获取元素**\n",
    "\n",
    "\n",
    "\n",
    "使用slice()获取最后n个元素。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 105,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[7, 8, 9, 10]\n",
      "8\n"
     ]
    }
   ],
   "source": [
    "my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n",
    "slicing = slice(-4, None)\n",
    "print(my_list[slicing])  # [4, 5, 6]\n",
    "\n",
    "print(my_list[-3])  # 4\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "使用slice()做切片任务。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 106,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Science\n"
     ]
    }
   ],
   "source": [
    "string = \"Data Science\"\n",
    "\n",
    "slice_object = slice(5, None)\n",
    "print(string[slice_object])   # Science\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍75、计算元素在元组中出现的次数**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 107,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3\n"
     ]
    }
   ],
   "source": [
    "my_tuple = ('a', 1, 'f', 'a', 5, 'a')\n",
    "\n",
    "print(my_tuple.count('a'))  # 3\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍76、获取元组中元素的索引**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 108,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n"
     ]
    }
   ],
   "source": [
    "my_tuple = ('a', 1, 'f', 'a', 5, 'a')\n",
    "\n",
    "print(my_tuple.index('f'))  #  2\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍77、步进获得元组**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 109,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(1, 4, 7, 10)\n"
     ]
    }
   ],
   "source": [
    "my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n",
    "\n",
    "print(my_tuple[::3])  # (1, 4, 7, 10)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍78、通过索引获取子元组**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 110,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(4, 5, 6, 7, 8, 9, 10)\n"
     ]
    }
   ],
   "source": [
    "my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n",
    "\n",
    "print(my_tuple[3:])  # (4, 5, 6, 7, 8, 9, 10)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍79、将列表、集合、字典中所有元素删除**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 111,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[]\n",
      "set()\n",
      "{}\n"
     ]
    }
   ],
   "source": [
    "my_list = [1, 2, 3, 4]\n",
    "my_list.clear()\n",
    "print(my_list)  # []\n",
    "\n",
    "my_set = {1, 2, 3}\n",
    "my_set.clear()\n",
    "print(my_set)  # set()\n",
    "\n",
    "my_dict = {\"a\": 1, \"b\": 2}\n",
    "my_dict.clear()\n",
    "print(my_dict)  # {}\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍80、合并集合**\n",
    "\n",
    "\n",
    "\n",
    "使用union()方法，返回一个新集合。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 112,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{1, 2, 3, 4, 5, 6}\n"
     ]
    }
   ],
   "source": [
    "first_set = {4, 5, 6}\n",
    "second_set = {1, 2, 3}\n",
    "\n",
    "print(first_set.union(second_set))  # {1, 2, 3, 4, 5, 6}\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "还可以使用update()方法，将第二个集合的元素插入到第一个集合中去。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 113,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{1, 2, 3, 4, 5, 6}\n"
     ]
    }
   ],
   "source": [
    "first_set = {4, 5, 6}\n",
    "second_set = {1, 2, 3}\n",
    "\n",
    "first_set.update(second_set)\n",
    "\n",
    "print(first_set)  # {1, 2, 3, 4, 5, 6}\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍81、在函数里输出结果**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 114,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Negative\n"
     ]
    }
   ],
   "source": [
    "def is_positive(number):\n",
    "    print(\"Positive\" if number > 0 else \"Negative\")  # Positive\n",
    "\n",
    "\n",
    "is_positive(-3)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍82、if语句中的多个条件**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 115,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Congratulations! You have passed all of the exams.\n"
     ]
    }
   ],
   "source": [
    "math_points = 51\n",
    "biology_points = 78\n",
    "physics_points = 56\n",
    "history_points = 72\n",
    "\n",
    "my_conditions = [math_points > 50, biology_points > 50,\n",
    "                 physics_points > 50, history_points > 50]\n",
    "\n",
    "if all(my_conditions):\n",
    "    print(\"Congratulations! You have passed all of the exams.\")\n",
    "else:\n",
    "    print(\"I am sorry, but it seems that you have to repeat at least one exam.\")\n",
    "# Congratulations! You have passed all of the exams.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍83、在一个if语句中，至少满足多个条件中的一个**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 116,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Congratulations! You have passed all of the exams.\n"
     ]
    }
   ],
   "source": [
    "math_points = 40\n",
    "biology_points = 78\n",
    "physics_points = 56\n",
    "history_points = 72\n",
    "\n",
    "my_conditions = [math_points > 50, biology_points > 50,\n",
    "                 physics_points > 50, history_points > 50]\n",
    "\n",
    "if any(my_conditions):\n",
    "    print(\"Congratulations! You have passed all of the exams.\")\n",
    "else:\n",
    "    print(\"I am sorry, but it seems that you have to repeat at least one exam.\")\n",
    "# Congratulations! You have passed all of the exams.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍84、任何非空字符串都为True**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 117,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "False\n"
     ]
    }
   ],
   "source": [
    "print(bool(\"Non empty\"))  # True\n",
    "print(bool(\"\"))  # False\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍85、任何非空列表、元组、字典都为True**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 118,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n",
      "False\n",
      "False\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "print(bool([]))  # False\n",
    "print(bool(set([])))  # False\n",
    "\n",
    "print(bool({}))  # False\n",
    "print(bool({\"a\": 1}))  # True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍86、None、False、0都为False**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 119,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n",
      "False\n",
      "False\n"
     ]
    }
   ],
   "source": [
    "print(bool(False))  # False\n",
    "print(bool(None))  # False\n",
    "print(bool(0))  # False\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍87、在函数中使用全局变量**\n",
    "\n",
    "\n",
    "\n",
    "在函数无法直接修改全局变量的值。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 120,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "string\n"
     ]
    }
   ],
   "source": [
    "string = \"string\"\n",
    "\n",
    "\n",
    "def do_nothing():\n",
    "  string = \"inside a method\"\n",
    "\n",
    "\n",
    "do_nothing()\n",
    "\n",
    "print(string)  # string\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "可通过修饰符global，修改全局变量的值。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 121,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "inside a method\n"
     ]
    }
   ],
   "source": [
    "string = \"string\"\n",
    "\n",
    "\n",
    "def do_nothing():\n",
    "    global string\n",
    "    string = \"inside a method\"\n",
    "\n",
    "\n",
    "do_nothing()\n",
    "\n",
    "print(string)  # inside a method\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍88、计算字符串或列表中元素的数量**\n",
    "\n",
    "\n",
    "\n",
    "使用collections中的Counter计算字符串或列表中元素的数量。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 122,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Counter({'a': 3, 'n': 2, 'B': 1})\n",
      "Counter({1: 5, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1})\n"
     ]
    }
   ],
   "source": [
    "from collections import Counter\n",
    "\n",
    "result = Counter(\"Banana\")\n",
    "print(result)  # Counter({'a': 3, 'n': 2, 'B': 1})\n",
    "\n",
    "\n",
    "result = Counter([1, 2, 1, 3, 1, 4, 1, 5, 1, 6])\n",
    "print(result)  # Counter({1: 5, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1})\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍89、检查2个字符串是否为相同**\n",
    "\n",
    "\n",
    "\n",
    "可以使用Counter()方法。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 123,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "True\n",
      "False\n"
     ]
    }
   ],
   "source": [
    "from collections import Counter\n",
    "\n",
    "\n",
    "def check_if_anagram(first_string, second_string):\n",
    "    first_string = first_string.lower()\n",
    "    second_string = second_string.lower()\n",
    "    return Counter(first_string) == Counter(second_string)\n",
    "\n",
    "\n",
    "print(check_if_anagram('testinG', 'Testing'))  # True\n",
    "print(check_if_anagram('Here', 'Rehe'))  # True\n",
    "print(check_if_anagram('Know', 'Now'))  # False\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "可以使用sorted()方法。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 124,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "True\n",
      "False\n"
     ]
    }
   ],
   "source": [
    "def check_if_anagram(first_word, second_word):\n",
    "    first_word = first_word.lower()\n",
    "    second_word = second_word.lower()\n",
    "    return sorted(first_word) == sorted(second_word)\n",
    "\n",
    "\n",
    "print(check_if_anagram(\"testinG\", \"Testing\"))  # True\n",
    "print(check_if_anagram(\"Here\", \"Rehe\"))  # True\n",
    "print(check_if_anagram(\"Know\", \"Now\"))  # False\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍90、使用itertools中的count计算元素的数量**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 125,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Current vowel: i\n",
      "Number of vowels found so far: 0\n",
      "Current vowel: i\n",
      "Number of vowels found so far: 1\n",
      "Current vowel: u\n",
      "Number of vowels found so far: 2\n",
      "Current vowel: a\n",
      "Number of vowels found so far: 3\n",
      "Current vowel: e\n",
      "Number of vowels found so far: 4\n",
      "Current vowel: e\n",
      "Number of vowels found so far: 5\n",
      "Current vowel: e\n",
      "Number of vowels found so far: 6\n"
     ]
    }
   ],
   "source": [
    "from itertools import count\n",
    "\n",
    "my_vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']\n",
    "\n",
    "current_counter = count()\n",
    "\n",
    "string = \"This is just a sentence.\"\n",
    "\n",
    "for i in string:\n",
    "    if i in my_vowels:\n",
    "        print(f\"Current vowel: {i}\")\n",
    "        print(f\"Number of vowels found so far: {next(current_counter)}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "输出如下。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Current vowel: i\n",
    "Number of vowels found so far: 0\n",
    "Current vowel: i\n",
    "Number of vowels found so far: 1\n",
    "Current vowel: u\n",
    "Number of vowels found so far: 2\n",
    "Current vowel: a\n",
    "Number of vowels found so far: 3\n",
    "Current vowel: e\n",
    "Number of vowels found so far: 4\n",
    "Current vowel: e\n",
    "Number of vowels found so far: 5\n",
    "Current vowel: e\n",
    "Number of vowels found so far: 6\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍91、对字符串或列表的元素进行次数排序**\n",
    "\n",
    "\n",
    "\n",
    "collections模块的Counter()，默认情况下是不会根据元素的频率对它们进行排序的。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 127,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Counter({2: 5, 1: 1, 3: 1})\n",
      "[(2, 5), (1, 1), (3, 1)]\n"
     ]
    }
   ],
   "source": [
    "from collections import Counter\n",
    "\n",
    "result = Counter([1, 2, 3, 2, 2, 2, 2])\n",
    "print(result)  # Counter({2: 5, 1: 1, 3: 1})\n",
    "print(result.most_common())  # [(2, 5), (1, 1), (3, 1)]\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "map()函数将给定函数应用于可迭代对象(列表、元组等)，然后返回结果(map对象)。\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "**▍92、查找列表中出现频率最高的元素**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 128,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a\n"
     ]
    }
   ],
   "source": [
    "my_list = ['1', 1, 0, 'a', 'b', 2, 'a', 'c', 'a']\n",
    "\n",
    "print(max(set(my_list), key=my_list.count))  # a\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍93、copy()和deepcopy()的区别**\n",
    "\n",
    "\n",
    "\n",
    "浅拷贝: 拷贝父对象，但是不会拷贝对象的内部的子对象。\n",
    "\n",
    "深拷贝: 拷贝父对象. 以及其内部的子对象。\n",
    "\n",
    "\n",
    "\n",
    "下面是一个copy()的例子。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 129,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1, 2, 831], ['a', 'b', 'c']]\n",
      "[[1, 2, 831], ['a', 'b', 'c']]\n"
     ]
    }
   ],
   "source": [
    "first_list = [[1, 2, 3], ['a', 'b', 'c']]\n",
    "\n",
    "second_list = first_list.copy()\n",
    "\n",
    "first_list[0][2] = 831\n",
    "\n",
    "print(first_list)  # [[1, 2, 831], ['a', 'b', 'c']]\n",
    "print(second_list)  # [[1, 2, 831], ['a', 'b', 'c']]\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这里是一个deepcopy()的例子。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 130,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1, 2, 831], ['a', 'b', 'c']]\n",
      "[[1, 2, 3], ['a', 'b', 'c']]\n"
     ]
    }
   ],
   "source": [
    "import copy\n",
    "\n",
    "first_list = [[1, 2, 3], ['a', 'b', 'c']]\n",
    "\n",
    "second_list = copy.deepcopy(first_list)\n",
    "\n",
    "first_list[0][2] = 831\n",
    "\n",
    "print(first_list)  # [[1, 2, 831], ['a', 'b', 'c']]\n",
    "print(second_list)  # [[1, 2, 3], ['a', 'b', 'c']]\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍94、访问字典中不存在的键时，避免报错**\n",
    "\n",
    "\n",
    "\n",
    "如果你想访问字典一个不存在的键，代码会报错。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 131,
   "metadata": {},
   "outputs": [
    {
     "ename": "KeyError",
     "evalue": "'age'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mKeyError\u001b[0m                                  Traceback (most recent call last)",
      "\u001b[1;32m~\\AppData\\Local\\Temp/ipykernel_20840/120010745.py\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m      1\u001b[0m \u001b[0mmy_dictonary\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;33m{\u001b[0m\u001b[1;34m\"name\"\u001b[0m\u001b[1;33m:\u001b[0m \u001b[1;34m\"Name\"\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;34m\"surname\"\u001b[0m\u001b[1;33m:\u001b[0m \u001b[1;34m\"Surname\"\u001b[0m\u001b[1;33m}\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mmy_dictonary\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;34m\"age\"\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mKeyError\u001b[0m: 'age'"
     ]
    }
   ],
   "source": [
    "my_dictonary = {\"name\": \"Name\", \"surname\": \"Surname\"}\n",
    "print(my_dictonary[\"age\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "错误如下。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "KeyError: 'age'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "可以通过使用defaultdict()，代码将不会报错。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 132,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "from collections import defaultdict\n",
    "\n",
    "my_dictonary = defaultdict(str)\n",
    "my_dictonary['name'] = \"Name\"\n",
    "my_dictonary['surname'] = \"Surname\"\n",
    "\n",
    "print(my_dictonary[\"age\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍95、构建迭代器**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 139,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "3\n",
      "5\n"
     ]
    }
   ],
   "source": [
    "class OddNumbers:\n",
    "    def __iter__(self):\n",
    "        self.a = 1\n",
    "        return self\n",
    "\n",
    "    def __next__(self):\n",
    "        x = self.a\n",
    "        self.a += 2\n",
    "        return x\n",
    "\n",
    "\n",
    "odd_numbers_object = OddNumbers()\n",
    "iterator = iter(odd_numbers_object)\n",
    "\n",
    "print(next(iterator))  # 1\n",
    "print(next(iterator))  # 3\n",
    "print(next(iterator))  # 5\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍96、删除列表的重复项**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 140,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3, 4, 5]\n"
     ]
    }
   ],
   "source": [
    "my_set = set([1, 2, 1, 2, 3, 4, 5])\n",
    "print(list(my_set))  # [1, 2, 3, 4, 5]\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍97、打印模块的安装位置**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 141,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<module 'pandas' from 'E:\\\\python39\\\\lib\\\\site-packages\\\\pandas\\\\__init__.py'>\n"
     ]
    }
   ],
   "source": [
    "import pandas\n",
    "\n",
    "print(pandas)  # <module 'torch' from '/Users/...'\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍98、使用not in检查一个值是否在列表中**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 142,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0, 2, 4, 6, 8]\n"
     ]
    }
   ],
   "source": [
    "odd_numbers = [1, 3, 5, 7, 9]\n",
    "even_numbers = []\n",
    "\n",
    "for i in range(9):\n",
    "    if i not in odd_numbers:\n",
    "        even_numbers.append(i)\n",
    "\n",
    "print(even_numbers)  # [0, 2, 4, 6, 8]\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍99、sort()和sorted()的区别**\n",
    "\n",
    "\n",
    "\n",
    "sort()：对原始列表进行排序\n",
    "\n",
    "sorted()：返回一个新的排序列表\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 143,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['bread', 'milk', 'tea']\n",
      "['milk', 'bread', 'tea']\n",
      "['bread', 'milk', 'tea']\n"
     ]
    }
   ],
   "source": [
    "groceries = ['milk', 'bread', 'tea']\n",
    "\n",
    "new_groceries = sorted(groceries)\n",
    "# new_groceries = ['bread', 'milk', 'tea']\n",
    "\n",
    "print(new_groceries)\n",
    "\n",
    "# groceries = ['milk', 'bread', 'tea']\n",
    "print(groceries)\n",
    "\n",
    "groceries.sort()\n",
    "\n",
    "# groceries = ['bread', 'milk', 'tea']\n",
    "print(groceries)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**▍100、使用uuid模块生成唯一ID**\n",
    "\n",
    "\n",
    "\n",
    "UUID代表唯一标识符。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 144,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3d8e2f01-4c27-11ec-95b6-002324df12cd\n",
      "dd862c5e-e2e1-4d3f-8373-350e22076b7e\n"
     ]
    }
   ],
   "source": [
    "import uuid\n",
    "\n",
    "# 根据主机ID、序列号和当前时间生成UUID\n",
    "print(uuid.uuid1())  # 308490b6-afe4-11eb-95f7-0c4de9a0c5af\n",
    "\n",
    "# 生成一个随机UUID\n",
    "print(uuid.uuid4())  # 93bc700b-253e-4081-a358-24b60591076a\n"
   ]
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "d3dd99316e4a8545b7b2cf42c2d8ce5a7faa985daf98d6f06c5f46664d86f14c"
  },
  "kernelspec": {
   "display_name": "Python 3.7.9 64-bit",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
